/**
 * 添加商品、添加购物车练习
 * 1. 两个切片：商品切片、购物车切片
 * 2. 商品切片：添加商品
 * 3. 购物车切片： 添加购物车、修改购买数量
 * 
 */
import {createSlice, configureStore} from '@reduxjs/toolkit'
// 1. 商品切片
const goodsSlice = createSlice({
    name:'goods',
    initialState:{
        goodsList:[] // goods {id:xxx,gname:'小米',price:1999}
    },
    reducers:{
        // 添加购物车
        addGoods(state, {payload}){ // payload {gname:'xx', price:'xx'}
            state.goodsList = [...state.goodsList, {
                id:Math.random().toString(36).slice(2),
                ...payload
            }]
        }
    }
})

const {addGoods} = goodsSlice.actions; // actionCreator获取完毕

// 购物车切片
const carSlice = createSlice({
    name:'car',
    initialState:{
        carList:[]
    },
    reducers:{
        // 添加购物车
        addCar(state, {payload}){ // payload {id,gname,price}
            state.carList = [...state.carList, {
                ...payload,
                buyNum:1 // 购买数量
            }]
        }
    }
})

const {addCar} = carSlice.actions

// 创建仓库
const store = configureStore({
    reducer:{
        goods:goodsSlice.reducer,
        car:carSlice.reducer
    }
})

// 监听仓库
store.subscribe(()=>{
    console.log(store.getState());
})

// 添加商品
store.dispatch(addGoods({gname:'小米手机', price:3999}))
store.dispatch(addGoods({gname:'华为手机', price:9}))


// 添加购物车
store.dispatch(addCar(store.getState().goods.goodsList[0]))
store.dispatch(addCar(store.getState().goods.goodsList[1]))